package com.example.redisdemo.controller;

import com.example.redisdemo.model.RedisInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import java.util.*;
@Controller
public class HashController {

    RedisInfo ri  = new RedisInfo();
    @RequestMapping(value = {"hash_list"})
    public ModelAndView allStrings(){

        Jedis jedis = new Jedis(ri.getRIp(),ri.getRPort());

        Set<String> keySets = new HashSet<>();
        keySets = jedis.keys("*");
        List<Map<String,String>> hashList = new ArrayList<>();
        for (String s:keySets){
            if(jedis.type(s).equals("hash")){
                hashList.add(jedis.hgetAll(s));
            }

        }

        ModelAndView mvc = new ModelAndView("hash_list");
        mvc.addObject("hashList",hashList);
        return mvc;
    }


    @PostMapping(value = {"hash_list"})
    public ModelAndView modifyHash(){
        RedisInfo ri  = new RedisInfo();
        Jedis jedis = new Jedis(ri.getRIp(),ri.getRPort());

        Set<String> keySets = new HashSet<>();
        keySets = jedis.keys("*");
        List<Map<String,String>> hashList = new ArrayList<>();
        for (String s:keySets){
            if(jedis.type(s).equals("hash")){
                hashList.add(jedis.hgetAll(s));
            }

        }

        ModelAndView mvc = new ModelAndView("hash_list");
        mvc.addObject("hashList",hashList);
        return mvc;
    }

    @RequestMapping(value = {"addHashName"})
    public  ModelAndView addHashName(@RequestParam("hashName")String hashName){
        Jedis jedis = new Jedis(ri.getRIp(),ri.getRPort());

        System.out.println(hashName);
        Map<String,String > map1 = new HashMap<>();
        map1.put("key","value");
        map1.put("key1","value");
        map1.put("key2","value");

//

        jedis.hmset(hashName,map1);

        Set<String> keySets =jedis.keys("*");
        List<Map<String,String>> hashList = new ArrayList<>();
        for (String s:keySets){
            if(jedis.type(s).equals("hash")){
                hashList.add(jedis.hgetAll(s));
            }

        }
        ModelAndView mvc = new ModelAndView("hash_list");
        mvc.addObject("hashList",hashList);
        return mvc;
    }
}
